#include "task_queue.h"
#include <stdio.h>
#include <stdlib.h>

TaskNode *
create_task (int task_id)
{
  TaskNode *new_task = (TaskNode *)malloc (sizeof (TaskNode));
  if (!new_task)
    {
      perror ("Memory allocation failed");
      exit (EXIT_FAILURE);
    }
  new_task->task_id = task_id;
  new_task->next = NULL;
  return new_task;
}

TaskNode *
reverse_task_queue_by_group (TaskNode *head, int k)
{
  TaskNode *hair = create_task (0);
  TaskNode *current_head = hair;
  TaskNode *current_tail = NULL;
  /* 用于辅助暂存任务队列 */
  hair->task_id = 0;
  hair->next = head;

  while (current_head->next != NULL)
    {
      current_tail = current_head;
      int i = 0;
      /* find current last node (number k) */
      for (i = 0; i < k && (current_tail != NULL); i++)
        current_tail = current_tail->next;
      if (current_tail == NULL)
        {
          printf("return\n");
          TaskNode *res = hair->next;
          hair->next = NULL;
          free_task_queue (hair);
          return res;
        }

      current_tail = current_head->next;
      /* reverse from head->next to tail */
      for (int i = 0; i < k - 1; i++)
        {
          TaskNode *tmp = current_tail->next;
          current_tail->next = tmp->next;
          tmp->next = current_head->next;
          current_head->next = tmp;
        }
      current_head = current_tail;
    }
  return hair->next;
}

void
free_task_queue (TaskNode *head)
{
  TaskNode *current = head;
  TaskNode *temp;
  while (current != NULL)
    {
      temp = current;
      current = current->next;
      free (temp);
    }
}

void
print_task_queue (TaskNode *head)
{
  TaskNode *current = head;
  while (current != NULL)
    {
      printf ("%d ", current->task_id);
      current = current->next;
    }
  printf ("\n");
}
